package com.cheetah.start.common.plugin.log;

import lombok.extern.slf4j.Slf4j;
import net.dreamlu.mica.core.utils.ThreadLocalUtil;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;


/**
 * 打印返回结果
 *
 * @author 25175
 * @date 2022/9/5 17:50
 */
@Slf4j
@RestControllerAdvice
public class ReturnBodyLog implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        Object start = ThreadLocalUtil.get("start");
        Object exception = ThreadLocalUtil.get("exception");
        Long c = null;
        boolean ex;
        if (start != null) {
            c = System.currentTimeMillis() - Long.parseLong(start.toString());
        }
        if (exception != null) {
            ex = Boolean.parseBoolean(exception.toString());
            if (ex) {
                log.warn("请求结果:[{}] 耗时:[{}]ms", o, c);
            }
        }
        return o;
    }


}
